import router from '@/router'
import { getToken } from '@/utils/auth'
import store from './store'
import { Message } from 'element-ui'

const whiteList = ['/login']
router.beforeEach((to, from, next) => {
  console.log('router.beforeEach---to', to)
  console.log('route.beforeEach---from', from)
  if (getToken()) {
    // 如果是登录页面，并且获取了token,则说明已经登录过，跳转到首页。跳转首页后会再次拦截,放置用户信息
    if (to.path === '/login') {
      next({ path: '/' })
    } else {
      // 判断是否获取到用户信息
      if (store.getters.roles.length === 0) {
        store.dispatch('GetInfo').then(res => {
          store.dispatch('GenerateRoutes').then(accessRoutes => {
            console.log('accessRoutes', JSON.parse(JSON.stringify(accessRoutes)))
            router.addRoutes(accessRoutes)
            // next()
            // 赋值以后会重新走一遍beforeEach,所以需要手动跳转
            // 这里的to是从路由跳转过来的，所以需要用...to
            next({ ...to })
          })
        }).catch(err => {
          Message.error(err)
        })
      } else {
        next()
      }
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      next()
    } else {
      next(`/login?redirect=${to.fullPath}`)
    }
  }
})
